package com.gqemf.service;

import com.gqemf.entity.EmfHistoryTemp;
import com.gqemf.entity.Emfhistory;
import com.gqemf.repository.EmfhistoryRepository;
import com.gqemf.util.CsvService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author chan
 */
@Service
public class EmfServiceImpl implements EmfService{

    private CsvService csvService;

    private EmfhistoryRepository emfhistoryRepository;

    @Autowired
    public EmfServiceImpl(CsvService csvService, EmfhistoryRepository emfhistoryRepository) {
        this.csvService = csvService;
        this.emfhistoryRepository = emfhistoryRepository;
    }

    @Override
    public List<Emfhistory> convertFromRecorders(File recorders) {
        List<Emfhistory> emfhistoryList = new ArrayList<>();
        //数据的特殊性，我们从第四行开始取数据
        List<EmfHistoryTemp> list = csvService.getCsvData(recorders,EmfHistoryTemp.class);
        Iterator<EmfHistoryTemp> iterator = list.iterator();
        while (iterator.hasNext()){
            emfhistoryList.add(new Emfhistory(iterator.next()));
        }
        return emfhistoryList;
    }

    @Transactional
    @Override
    public Integer saveEmfRecorders(List<Emfhistory> emfhistoryList) {
        List<Emfhistory> list = emfhistoryRepository.saveAll(emfhistoryList);
        return list.size();
    }

    @Override
    public Integer saveEmfRecorders(File recorders) {
        return null;
    }

    @Async("asyncServiceExecutor")
    @Override
    public void saveEmf(Emfhistory emfhistory) {
        Emfhistory emf = emfhistoryRepository.save(emfhistory);
    }

    @Override
    public List<Emfhistory> getAllEmfHistories() {
        return emfhistoryRepository.findAll();
    }

    @Override
    public Boolean checkIfLatestData(List<Emfhistory> emfhistoryList) {
        boolean check = false;
        Emfhistory latestDataFromDataSource = emfhistoryRepository.findFirstByOrderByIdDesc();
        Emfhistory lastItemInList = emfhistoryList.get(emfhistoryList.size() - 1);
        if(latestDataFromDataSource != null && !latestDataFromDataSource.getDateAndTime().equals(lastItemInList.getDateAndTime())){
            check = true;
        }
        if(latestDataFromDataSource == null){
            check = true;
        }
        return check;
    }
}
